package com.project.XXXX.identification;

import java.io.IOException;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpRequest;

import com.google.gson.Gson;
import com.project.XXXX.tools.ProjectTools;

public class IndentifyFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		if (StringUtils.endsWithAny(req.getRequestURL(), "getMessage.do", "Login.do", "register.do", "getProvince.do",
				"getCities.do", "getCountries.do", "getCountriesbycity.do", "showByTypeandPlaceCount.do",
				"showByTypeandPlace.do", "showItemDetail.do","getPlaceByName.do","validateCode.do") || StringUtils.contains(req.getRequestURL(), "/api"))
			chain.doFilter(request, response);
		else {if (session.getAttribute("User") == null||session.getAttribute("EEinfo")==null||session.getAttribute("ERinfo")==null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("error", "invalid_request");
			map.put("error_description", "Wrong username or password");
			String j = new Gson().toJson(map);
			resp.setStatus(403);
			ProjectTools.ResponseOut(resp, j);
		} else
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
